﻿using A.M.ETO;
using DotNetCore.CAP;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using MiniExcelLibs;
using Newtonsoft.Json;
using O.M.Production.ErrorCodeEnum;
using Public_Class_Library;
using System.Drawing.Printing;
using System.Linq.Expressions;
using System.Net.WebSockets;
using W.M.Materiel.Application.DTO;
using W.M.Materiel.Application.IServices;
using W.M.Materiel.Application.Services;
using W.M.Materiel.Domain.Entity;
using W.M.Materiel.Infrastruecure.DTO;
using W.M.Materiel.Infrastruecure.Repository;
using W.M.Materiel.Read.API.DTO;

namespace W.M.Materiel.Read.API.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class Bom_management_tableController : ControllerBase
    {
        private readonly IBom_management_tableServices bom_Management_TableServices;
        private readonly Cross_service_Helper cross_Service_Helper;
        private readonly ICapPublisher capPublisher;

        public Bom_management_tableController(IBom_management_tableServices bom_Management_TableServices, Cross_service_Helper cross_Service_Helper, ICapPublisher capPublisher)
        {
            this.bom_Management_TableServices = bom_Management_TableServices;
            this.cross_Service_Helper = cross_Service_Helper;
            this.capPublisher = capPublisher;
        }

        /// <summary>
        /// 显示BOM信息+查询+分页
        /// </summary>
        /// <param name="pageSize">页容量</param>
        /// <param name="pageIndex">当前页</param>
        /// <param name="number">查询条件:BOM编号</param>
        /// <returns>BOM信息</returns>
        [HttpGet]
        public IActionResult GetBOMrelation(int pageSize, int pageIndex, string? number)
        {
            int totalCount;
            int pageCount;
            var list= bom_Management_TableServices.GetBOMrelation(pageSize, pageIndex, number,out totalCount,out pageCount);
            return Ok(new
            {
                totalCount,pageCount,list
            });
        }


        /// <summary>
        /// 显示BOM
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetBOMrelations()
        {
            var list= bom_Management_TableServices.GetBOMrelations();
            return Ok(list);
        }

        /// <summary>
        /// 显示BOM详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetProduct_BOMDTOs(string? id)
        {
            var list = bom_Management_TableServices.GetProduct_BOMDTOs(id);
            return Ok(list);
        }

        /// <summary>
        /// 显示工艺流程详细
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetCreatedinfos(string? id)
        {
            var list = bom_Management_TableServices.GetCreatedinfos(id);
            return Ok(list);
        }

        /// <summary>
        /// 反填BOM数据
        /// </summary>
        /// <param name="bom_number">BOM编号</param>
        /// <returns>BOM实体</returns>
        [HttpGet]
        public async Task<IActionResult> Getbackfill(string? bom_number)
        {
            var list = await bom_Management_TableServices.Getbackfill(bom_number);
            return Ok(list);
        }


        /// <summary>
        /// 添加BOM
        /// </summary>
        /// <param name="c">BOM实体</param>
        /// <returns>统一返回格式</returns>
        [HttpPost]
        public async Task<IActionResult> AddInfo(BOM_TableDTO c)
        {
            var list = await bom_Management_TableServices.AddInfo(c);
            return Ok(list);
        }

        [HttpGet]
        [CapSubscribe("GetBomName")]
        public async Task<IActionResult> GetAddXsInfor(string? id)
        {
            var list = await bom_Management_TableServices.GetAddXsInfor(id);
            return Ok(list);
        }

        /// <summary>
        /// 审批的消息队列
        /// </summary>
        /// <param name="ProductDTO"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult AddInforMQ(ProductDTO ProductDTO)
        {
            //申请成功需要传一个消息队列;
            capPublisher.Publish("addStaffInforDTOGer", ProductDTO);
            return Ok("");
        }

        /// <summary>
        /// 先获取所有的审批
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetProccInfir()
        {
            var res = "http://10.31.59.5:5123/api/Approval_form/GetappList";
            var mes = await cross_Service_Helper.Get(res);
            var ges = JsonConvert.DeserializeObject<List<BOMDTO>>(mes);
            var list = ges.Where(c => c.approval_name == "BOM系统").FirstOrDefault();
            return Ok(list.apprpvalTwoDTO);
        }


        /// <summary>
        /// 删除BOM
        /// </summary>
        /// <param name="c">BOM实体</param>
        /// <returns>统一返回格式</returns>
        [HttpPost]
        public async Task<IActionResult> DeleteBOM(string? c)
        {
            var list = await bom_Management_TableServices.DeleteBOM(c);
            return Ok(list);
        }

        /// <summary>
        /// 修改BOM信息
        /// </summary>
        /// <param name="c">BOM实体</param>
        /// <returns>统一返回格式</returns>
        [HttpPost]
        public async Task<IActionResult> GetUpdateBOM(Bom_management_tableDTO c)
        {
            var list = await bom_Management_TableServices.GetUpdateBOM(c);
            return Ok(list);
        }

        /// <summary>
        /// 工艺流程
        /// </summary>
        /// <param name="pageSize">当前页</param>
        /// <param name="pageIndex">页容量</param>
        /// <param name="id">查询条件:id</param>
        /// <returns>工艺流程</returns>
        [HttpGet]
        public IActionResult GetProcessFlow(int pageSize, int pageIndex, string? id)
        {
            var obj = cross_Service_Helper.Get($"http://10.31.59.2:8088/api/Read_Process_Flow/Get_process_flow_Page?process_flow_id_name={id}&pageSize={pageSize}&pageIndex={pageIndex}").Result;
            var jsonObj = JsonConvert.DeserializeObject<ApiResult>(obj);

            return Ok(jsonObj);
        }

        /// <summary>
        /// 上传文件到七牛云
        /// </summary>
        /// <param name="file">文件</param>
        /// <returns>是否成功</returns>
        [HttpPost]
        public IActionResult FileList(IFormFile file)
        {
            var list=FileHelper.UploadFile(file);
            return Ok(list);
        }

        /// <summary>
        /// 导出
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult ExportTiExcel()
        {
            var list = bom_Management_TableServices.GetShowInfor();
            var steram = new MemoryStream();
            steram.SaveAs(list);
            steram.Seek(0, SeekOrigin.Begin);
            return new FileStreamResult(steram, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
            {
                FileDownloadName = "BOM信息"
            };
        }


        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult BOMimport(IFormFile file)
        {
            if (file == null || file.Length == 0)
            {
                return BadRequest("为选择文件或文件为空");
            }

            var formfile = Request.Form.Files[0];
            var fileName = formfile.FileName;
            var fileExtension = Path.GetExtension(formfile.FileName);
            if (fileExtension != ".xlsx" && fileExtension != ".xls")
            {
                return BadRequest("文件格式错误!");
            }
            ApiReturn<string> apiReturn = new ApiReturn<string>();
            using (var steam = new MemoryStream())
            {
                formfile.CopyTo(steam);
                steam.Position = 0;
                var list = steam.Query<bom_management_table>();
                steam.Position = 0;
                var info = list.Select(x => new bom_management_table
                {
                    bom_number = x.bom_number,
                    bom_topic = x.bom_topic,
                    daily_output = x.daily_output,
                    default_bom = x.default_bom,
                    finished_number = x.finished_number,
                    name_finished_product = x.name_finished_product,
                    product_number = x.product_number,
                    remark = x.remark,
                    type_finished_product = x.type_finished_product,
                    version_number = x.version_number,
                }).ToList();

                bom_Management_TableServices.AddInfor_Batch_Async(info);
            }
            apiReturn.Code = 200;
            apiReturn.Message = "导入成功";
            return Ok(apiReturn);
        }
    }
}
